import React, { Component } from "react";
import { Form, Radio, Input, DatePicker } from "antd";
import TheTable from "@/components/TheTable"
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination"
import { apiHotelOrderPage } from "../../../request/hotelOrder";
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable } from "@/utils/exportTable";
import store from "@/store/store"
const { Search } = Input;
const { RangePicker } = DatePicker;
export default class Order extends Component {
  constructor() {
    super()
    this.formRef = React.createRef()
    this.formRefs = React.createRef()
    this.state = {
      columns: [
        {
          title: "订单编号",
          dataIndex: "orderCode",
          key: "orderCode",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        {
          title: "用户手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
        },
        {
          title: "订单状态",
          dataIndex: "orderState",
          key: "orderState",
          render: (text, record) => {
            let orderStatus = ''
            switch (text) {
              case '0':
                orderStatus = '已结束'
                break
              case '1':
                orderStatus = '待付款'
                break
              case '2':
                orderStatus = '待入住'
                break
              case '3':
                orderStatus = '已入住'
                break
              case '4':
                orderStatus = '已取消'
                break
              case '9':
                orderStatus = '交易成功'
                break
              default:
                break
            }
            return orderStatus
          }
        },
        {
          title: "订单金额",
          dataIndex: "orderTotalPrice",
          key: "orderTotalPrice",
          render: (text, record) => {
            return record.orderTotalPrice ? <React.$Price price={record.orderTotalPrice}></React.$Price> : '/'
          }
        },
        // {
        //   title: "优惠券名称",
        //   dataIndex: "couponTitle",
        //   key: "couponTitle",
        //   render: (text, record) => {
        //     return record.couponTitle ? record.couponTitle : '/'
        //   }
        // },
        {
          title: "优惠金额",
          dataIndex: "couponTotal",
          key: "couponTotal",
          render: (text, record) => {
            return record.couponTotal ? <React.$Price price={text}></React.$Price> : '/'
          }
        },
        {
          title: "实付金额",
          dataIndex: "orderPayPrice",
          key: "orderPayPrice",
          render: (text, record) => {
            return record.orderPayPrice ? <React.$Price price={record.orderPayPrice}></React.$Price> : '/'
          }
        },
        {
          title: "收银备注",
          dataIndex: "cashierRemark",
          key: "cashierRemark",
          render: (text, record) => {
            return record.cashierRemark ? record.cashierRemark : '/'
          }
        },
        {
          title: "付款方式",
          dataIndex: "payWay",
          key: "payWay",
          render: (text, record) => {
            let payWay = ''
            switch (record.payWay) {
              case 'WeChat':
                payWay = '微信'
                break;
              case 'Alipay':
                payWay = '支付宝'
                break;
              case 'UnionPay':
                payWay = "银联"
                break;
              case 'YsPay':
                payWay = "银行卡支付"
                break;
              case 'Cash':
                payWay = "现金"
                break;
              case 'Wallet':
                payWay = "余额"
                break;
              case 'Fix':
                payWay = "混合支付"
                break;
              case 'RemoteAlipay':
                payWay = "扫码支付（支付宝）"
                break;
              case 'RemoteWeChat':
                payWay = "扫码支付（微信）"
                break;
              default:
                payWay = "未知支付方式"
            }
            return payWay
          }
        },
        {
          title: "售后状态",
          dataIndex: "salesReturnStatus",
          key: "salesReturnStatus",
          render: (text, record) => {
            let str = ''
            switch (text) {
              case '0':
                str = '已关闭'
                break
              case '1':
                str = '退款中'
                break
              case '4':
                str = '退款失败'
                break
              case '9':
                str = '退款成功'
                break
              default:
                str = '暂无'
            }
            return text = str
          }
        },
        {
          title: "退款金额",
          dataIndex: "returnPrice",
          key: "returnPrice",
          render: (text, record) => {
            return record.returnPrice ? <React.$Price price={text}></React.$Price> : '/'
          }
        },
        {
          title: "下单日期",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "核销时间",
          dataIndex: "checkInTime",
          key: "checkInTime",
          render: (text, record) => {
            return record.checkInTime ? record.checkInTime : '/'
          }
        },
        {
          title: "房间名称",
          dataIndex: "serviceName",
          key: "serviceName",
        },
        {
          title: "房间号码",
          dataIndex: "roomName",
          key: "roomName",
        },
        {
          title: "房间价格",
          dataIndex: "serviceRealPrice",
          key: "serviceRealPrice",
          render: (text, record) => {
            return record.serviceRealPrice ? <React.$Price price={text}></React.$Price> : '/'
          }
        },
        {
          title: "入住日期",
          dataIndex: "checkInTime",
          key: "checkInTime",
          render: (text, record) => {
            return record.checkInTime ? record.checkInTime : '/'
          }
        },
        {
          title: "离店日期",
          dataIndex: "checkOutTime",
          key: "checkOutTime",
          render: (text, record) => {
            return record.checkOutTime ? record.checkOutTime : '/'
          }
        },
        {
          title: "入住天数",
          dataIndex: "daysSum",
          key: "daysSum",
          render: (text, record) => {
            return record.daysSum !== null ? record.daysSum : '0'
          }
        },   
        {
          title: "操作",
          fixed: 'right',
          render: (text, record) => {
            return <div>
              <TheButton hasPermi={['hotelOrder:list:details']} onClick={() => this.props.history.push('/hotelOrder/list/' + record.hotelOrderId)}>订单详情</TheButton>
            </div>
          }
        },
      ],
      dataSource: [],
      beforeDaysNum: '0', //最近几天
      endTime: '', // 自定义开始时间
      startTime: '', // 自定义结束时间
      orderState: '', // 订单状态
      memberMobile: '', // 手机号码
      orderCode: '', // 订单编号
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: '',
      exportLoading: false
    }
  }

  componentDidMount() {
    let searchParams = store.getState().searchValue
    if (searchParams && searchParams.pathName === "hotelOrderList") {
      let { pageNo, pageSize, beforeDaysNum, endTime, startTime, orderState, memberMobile, orderCode } = searchParams
      this.formRef.setFieldsValue({
        checkInTime: beforeDaysNum,
        orderState: orderState,
        memberMobile: memberMobile,
        orderCode: orderCode
      });
      this.formRefs.setFieldsValue({
        memberMobile: memberMobile,
        orderCode: orderCode
      });
      this.setState({
        beforeDaysNum: beforeDaysNum,
        orderState: orderState ? orderState : '',
        endTime: endTime ? endTime : '',
        startTime: startTime ? startTime : '',
        memberMobile: memberMobile ? memberMobile : '',
        orderCode: orderCode ? orderCode : '',
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.getData()
      })
    } else {
      this.getData()
    }
  }

  // 订单列表
  getData = async () => {
    const { pageData, orderState, beforeDaysNum, startTime, endTime, memberMobile, orderCode } = this.state
    let params = {
      beforeDaysNum, startTime, endTime, memberMobile, orderCode, ...pageData, orderState
    }
    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        pathName: 'hotelOrderList',
        ...params
      }
    })
    let res = await apiHotelOrderPage({ ...pageData, orderState, beforeDaysNum: beforeDaysNum === '1' ? '' : beforeDaysNum, startTime, endTime, memberMobile, orderCode, type: 'Y', })
    if (res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize,
        },
        total: res.totalCount,
      })
    }
  }
  // 分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData();
    })
  }
  // 快速筛选时间
  screenTime = (e) => {
    this.setState({
      beforeDaysNum: e.target.value,
      startTime: '',
      endTime: '',
      pageData: {
        pageNo: 1,
        pageSize: 10,
      }
    }, () => {
      this.getData()
    })
  }
  // 自定义时间
  customTime = (time) => {
    console.log(time);
    this.setState({
      startTime: time && time.length ? getDateTime3(time[0]) : '',
      endTime: time && time.length ? getDateTime3(time[1]) : ''
    }, () => {
      this.getData()
    })
  }
  // 手机号码搜索
  onMobileSearch(e) {
    this.setState({
      memberMobile: e,
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  // 订单编号
  onOrderCodeSearch = (e) => {
    this.setState({
      orderCode: e,
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  // 导出
  toExportTable = async () => {
    this.setState({
      exportLoading: true,
    })
    const { pageData, orderState, beforeDaysNum, startTime, endTime, memberMobile, orderCode } = this.state
    await apiHotelOrderPage({ ...pageData, orderState, beforeDaysNum: beforeDaysNum === '1' ? '' : beforeDaysNum, startTime, endTime, memberMobile, orderCode, type: 'N', })
      .then((res) => {
        console.log(res);
        if (res.code === 0 && res.data.length > 0) {
          let isSheet = true,
            fileName = '酒店订单列表',
            tH_data =
              [
                { prop: 'orderCode', title: '订单编号' },
                { prop: 'nickName', title: '用户昵称' },
                { prop: 'memberMobile', title: '用户手机号' },
                { prop: 'orderState', title: '订单状态' },
                { prop: 'orderTotalPrice', title: '订单金额' },
                { prop: 'couponTitle', title: '优惠券名称' },
                { prop: 'couponTotal', title: '优惠金额' },
                { prop: 'orderPayPrice', title: '实付金额' },
                { prop: 'cashierRemark', title: '收银备注' },
                { prop: 'payWay', title: '付款方式' },
                { prop: 'salesReturnStatus', title: '售后状态' },
                { prop: 'returnPrice', title: '退款金额' },
                { prop: 'checkInTime', title: '核销时间' },
                { prop: 'createTime', title: '下单日期' },
                { prop: 'serviceName', title: '房间名称' },
                { prop: 'roomName', title: '房间号码' },
                { prop: 'serviceRealPrice', title: '房间价格' },
                { prop: 'checkInTime', title: '入住日期' },
                { prop: 'checkOutTime', title: '离店日期' },
                { prop: 'daysSum', title: '入住天数' },
              ]

          let tB_data = res.data.map((item) => {
            let orderState = ''
            switch (item.orderState) {
              case '0':
                orderState = '已结束'
                break
              case '1':
                orderState = '待付款'
                break
              case '2':
                orderState = '待入住'
                break
              case '3':
                orderState = '已入住'
                break
              case '4':
                orderState = '已取消'
                break
              case '9':
                orderState = '交易成功'
                break
            }
            let payWay = ''
            switch (item.payWay) {
              case 'WeChat':
                payWay = '微信'
                break;
              case 'Alipay':
                payWay = '支付宝'
                break;
              case 'UnionPay':
                payWay = "银联"
                break;
              case 'YsPay':
                payWay = "银行卡支付"
                break;
              case 'Cash':
                payWay = "现金"
                break;
              case 'Wallet':
                payWay = "余额"
                break;
              case 'Fix':
                payWay = "混合支付"
                break;
              case 'RemoteAlipay':
                payWay = "扫码支付（支付宝）"
                break;
              case 'RemoteWeChat':
                payWay = "扫码支付（微信）"
                break;
              default:
                payWay = "未知支付方式"
                break;
            }
            let salesReturnStatus = ''
            switch (item.salesReturnStatus) {
              case '0':
                salesReturnStatus = '已关闭'
                break
              case '1':
                salesReturnStatus = '退款中'
                break
              case '4':
                salesReturnStatus = '退款失败'
                break
              case '9':
                salesReturnStatus = '退款成功'
                break
              default:
                salesReturnStatus = '暂无'
            }
            return {
              orderCode: item.orderCode,
              nickName: item.nickName,
              memberMobile: item.memberMobile,
              orderState: orderState,
              orderTotalPrice: (item.orderTotalPrice / 100).toFixed(2),
              couponTitle: item.couponTitle ? item.couponTitle : '/',
              couponTotal: item.couponTotal ? (item.couponTotal / 100).toFixed(2) : '/',
              orderPayPrice: (item.orderPayPrice / 100).toFixed(2),
              cashierRemark: item.cashierRemark ? item.cashierRemark : "/",
              payWay: payWay,
              salesReturnStatus: salesReturnStatus,
              returnPrice: item.returnPrice ? (item.returnPrice / 100).toFixed(2) : "/",
              checkInTime: item.checkInTime ? item.checkInTime : '/',
              serviceName: item.serviceName,
              roomName: item.roomName,
              serviceRealPrice: (item.serviceRealPrice / 100).toFixed(2),
              createTime: item.createTime,
              checkInTime: item.checkInTime ? item.checkInTime : '/',
              checkOutTime: item.checkOutTime ? item.checkOutTime : '/',
              daysSum: item.daysSum !== null ? item.daysSum : '0',
            };
          });

          this.setState({ exportLoading: false });
          exportSheetTable({
            fileName,
            tH_data,
            tB_data,
            isSheet,
          });
        } else {
          React.$message({
            type: "warning",
            content: "导出操作失败,请重试",
          });
          this.setState({ exportLoading: false });
        }
      })
      .catch((err) => {
        React.$message({
          type: "warning",
          content: "导出操作失败,请重试",
        });
        this.setState({ exportLoading: false });
      });
  }
  // 订单状态
  orderStatusChange = (e) => {
    this.setState({
      orderState: e.target.value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {

      this.getData()
    })

  }
  render() {
    let { columns, dataSource, pageData, total, orderState, beforeDaysNum, exportLoading } = this.state
    return (
      <>
        <div className="p-layout-box commodity-content">
          <div className="p-search-box" style={{ marginBottom: 20 }}>
            <Form
              ref={(ref) => this.formRef = ref}
            >
              <Form.Item
                name="checkInTime"
                label="快速筛选"
              >
                <Radio.Group buttonStyle="solid" value={beforeDaysNum}>
                  <Radio.Button style={{ marginRight: 20 }} value="0" onChange={this.screenTime}>全部</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="7" onChange={this.screenTime}>最近7天</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="14" onChange={this.screenTime}>最近14天</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="1" onChange={this.screenTime} >自定义日期</Radio.Button>
                </Radio.Group>
                {
                  beforeDaysNum === '1' ? <RangePicker onChange={this.customTime} /> : ''
                }
              </Form.Item>
              <Form.Item
                name="orderState"
                label="订单状态"
              >
                <Radio.Group defaultValue={orderState} buttonStyle="solid" onChange={this.orderStatusChange}>
                  <Radio.Button style={{ marginRight: 20 }} value="">全部</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="1">待付款</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="2">待入住</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="3">已入住</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="4">已取消</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="9">交易成功</Radio.Button>
                  <Radio.Button style={{ marginRight: 20 }} value="0">已结束</Radio.Button>
                </Radio.Group >
              </Form.Item>
            </Form>
            <Form layout={'inline'} ref={(ref) => this.formRefs = ref}>
              <Form.Item label="手机号码" name="memberMobile">
                <Search type="number" placeholder="请输入手机号码" allowClear={true} onSearch={(e) => this.onMobileSearch(e)} style={{ width: 200 }} />
              </Form.Item>
              <Form.Item label="订单编号" name="orderCode">
                <Search placeholder="请输入订单编号" allowClear={true} onSearch={(e) => this.onOrderCodeSearch(e)} style={{ width: 200 }} />
              </Form.Item>
              <TheButton hasPermi={['hotelOrder:list:export']} size="middle" type="default" onClick={() => { this.toExportTable() }} loading={exportLoading}>导出</TheButton>
            </Form>
          </div>
          <TheTable columns={columns} dataSource={dataSource} />
          <ThePagination pageNo={pageData.pageNo} pageSize={pageData.pageSize} total={total} pageChange={this.pageChange} />
        </div>

      </>

    )
  }
}
